Loading SharePoint Data
185
import {ISPList} from './ISPList';
import {ISPListItem} from './ISPListItem';
export interface ISPDataService{
getLists():Promise<ISPList[]>;
getListItems(ListID:string, MaxItems:number):Promise<ISPListItem[]>;
}
Now implement the method on both the mock and the live data service.
MOCKDATASERVICE.TS
import { ISPListItem } from '../interfaces/ISPListItem';
Inside the MockDataService class, implement the getListItems method. Let’s use a random array that
contains the number of elements we want to get from our service.
public getListItems(ListID: string, MaxItems: number): Promise<ISPListItem[]>
{
var mockData: ISPListItem[] = [];
for (let i = 0, max = MaxItems; i < max; i += 1) {
mockData.push({ id: i, title: "Item" + i });
}
return Promise.resolve(mockData);
}
SHAREPOINTDATASERVICE.TS
import { ISPListItem } from '../interfaces/ISPListItem';
Inside the SharePointDataService class, implement the getListItems method.
Notice that into the REST call we pass in our second property, the MaxItems, to limit the maximum
item count.
public getListItems(ListID: string, MaxItems: number): Promise<ISPListItem[]>
{
let requestUrl: string =
this.context.pageContext.web.absoluteUrl +
"/_api/web/lists(guid'" + ListID + "')/items/?$top=" + MaxItems +
"&$select=id,Title";
return this.context.spHttpClient
.get(requestUrl, SPHttpClient.configurations.v1)
.then((response: SPHttpClientResponse) => response.json())
.then((jsonData: any) => {
return jsonData.value.map((element) => {
return { id: element.Id, title: element.Title };
});
}
})
.catch((error) => {
console.log("Something went wrong!");
console.log(error);
return [];
});
Let’s now get the list item data in the web part. Create a method loadListData. This method will first
get the data from the data service and then render it inside the web part.
LISTDATAWEBPART.TS
import { ISPListItem } from '../../interfaces/ISPListItem';
Copyright 2000- 2018 by U2U Training nv/sa, Belgium – For use in U2U courses only. Visit www.u2u.be